package io.wins.vertx.core;

import java.util.HashMap;
import java.util.Map;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.wins.vertx.entity.Codelist;
import io.wins.vertx.service.CodelistService;

public enum CodelistManager {
    CODE_LIST;

    private Map<String, Codelist> store;
    private final Logger logger = LoggerFactory.getLogger(CodelistManager.class);

    public void init(final Vertx vertx, final Handler<AsyncResult<String>> done) {
        if (this.store == null) {
            this.logger.info("Start init codelist manager...");
            final CodelistService codelistService = new CodelistService(vertx);
            codelistService.initCodeList(result -> {
                if (result.succeeded()) {
                    this.setCodeList(result.result());
                    this.logger.info("Finish init codelist manager...");
                    done.handle(Future.succeededFuture());
                } else {
                    this.logger.error("Error happened when init Codelist!", result.cause());
                    done.handle(Future.failedFuture(result.cause()));
                }
            });
        }
    }

    private void setCodeList(final JsonArray result) {
        this.store = new HashMap<>();
        for (final Object jsonCode : result.getList()) {
            final Codelist codelist = new Codelist((JsonObject) jsonCode);
            this.store.put(codelist.getCode(), codelist);
        }
    }

    public Codelist getCodeListByCode(final String code) {
        return this.store.get(code);
    }

    public Map<String, Codelist> getAllCodelist() {
        return this.store;
    }
}
